package com.edu.servlet;

import com.edu.entity.User;
import com.edu.entity.userFollow;
import com.edu.service.informationModificationService;
import com.edu.service.impl.informationModificationServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@WebServlet("/updateProfile")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
    maxFileSize = 1024 * 1024 * 10,      // 10 MB
    maxRequestSize = 1024 * 1024 * 50    // 50 MB
)
public class UpdateProfileServlet extends HttpServlet {
    private informationModificationService service = new informationModificationServiceImpl();
    private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    private static final String SAVE_DIR = "C:\\uploads"; // 头像保存目录

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 设置字符编码为UTF-8，解决中文乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        PrintWriter out = null;
        
        try {
            // 确保保存目录存在
            File saveDir = new File(SAVE_DIR);
            if (!saveDir.exists()) {
                boolean created = saveDir.mkdirs();
                if (!created) {
                    throw new IOException("无法创建头像保存目录: " + SAVE_DIR);
                }
            }
            
            // 调试输出：打印所有接收到的参数
            System.out.println("==== 接收到的参数 ====");
            System.out.println("userId: " + request.getParameter("userId"));
            System.out.println("username: " + request.getParameter("username"));
            System.out.println("sex: " + request.getParameter("sex"));
            System.out.println("birthday: " + request.getParameter("birthday"));
            System.out.println("province: " + request.getParameter("province"));
            System.out.println("city: " + request.getParameter("city"));
            System.out.println("district: " + request.getParameter("district"));
            System.out.println("address: " + request.getParameter("address"));
            System.out.println("introduce: " + request.getParameter("introduce"));
            System.out.println("phoneNum: " + request.getParameter("phoneNum"));
            System.out.println("password: " + request.getParameter("password"));
            System.out.println("======================");
            
            // 创建userFollow对象
            User user = new User();
            user.setUserid(Integer.parseInt(request.getParameter("userId")));
            
            // 处理用户名
            String username = request.getParameter("username");
            if (username != null && !username.isEmpty()) {
                user.setUsername(username);
            } else {
                // 使用默认用户名
                user.setUsername("数码达人小王");
                System.out.println("使用默认用户名");
            }
            
            // 处理性别参数
            String sexParam = request.getParameter("sex");
            int sexValue = 3; // 默认保密
            if (sexParam != null) {
                try {
                    sexValue = Integer.parseInt(sexParam);
                } catch (NumberFormatException e) {
                    // 如果无法解析为数字，使用默认值
                    System.err.println("性别参数格式错误: " + sexParam);
                }
            }
            user.setSex(sexValue);
            
            // 处理电话号码
            String phoneNum = request.getParameter("phoneNum");
            if (phoneNum != null) {
                user.setPhonenum(phoneNum);
            }
            
            // 处理生日日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String birthdayStr = request.getParameter("birthday");
            if (birthdayStr != null && !birthdayStr.isEmpty()) {
                try {
                    Date birthday = sdf.parse(birthdayStr);
                    user.setBrithday(birthday);
                    System.out.println("成功解析生日: " + birthday);
                } catch (ParseException e) {
                    System.err.println("生日格式错误: " + birthdayStr);
                    // 使用默认生日
                    try {
                        user.setBrithday(sdf.parse("1995-05-15"));
                        System.out.println("使用默认生日: 1995-05-15");
                    } catch (ParseException ex) {
                       
                    }
                }
            } else {
                // 使用默认生日
                try {
                    user.setBrithday(sdf.parse("1995-05-15"));
                    System.out.println("使用默认生日: 1995-05-15");
                } catch (ParseException e) {
                    // 忽略解析错误
                }
            }
            
            // 处理地址 - 优先使用组合地址
            String address = request.getParameter("address");
            if (address == null || address.isEmpty()) {
                // 组合地址
                String province = request.getParameter("province");
                String city = request.getParameter("city");
                String district = request.getParameter("district");
                
                province = (province != null) ? province : "";
                city = (city != null) ? city : "";
                district = (district != null) ? district : "";
                
                address = province + " " + city + " " + district;
            }
            System.out.println("最终地址: " + address);
            user.setAddress(address != null ? address.trim() : "");
            
            // 处理自我介绍
            String introduce = request.getParameter("introduce");
            if (introduce != null) {
                user.setIntroduce(introduce);
            }
            
            // 处理密码更新
            String password = request.getParameter("password");
            if (password != null && !password.isEmpty()) {
                user.setPassword(password);
            }
            
            // 处理头像上传
            javax.servlet.http.Part filePart = request.getPart("avatar");
            if (filePart != null && filePart.getSize() > 0) {
                String fileName = generateUniqueFileName(filePart.getSubmittedFileName());
                Path filePath = Paths.get(SAVE_DIR, fileName);
                Files.copy(filePart.getInputStream(), filePath);
                user.setHeadimg(fileName);
                System.out.println("头像已保存: " + fileName);
            } else {
                // 使用默认头像
                user.setHeadimg("/default-avatar.png");
                System.out.println("使用默认头像");
            }
            
            // 调用服务层更新用户信息
            boolean success = service.updateUserInformation(user);
            
            result.put("success", success);
            result.put("message", success ? "资料更新成功" : "资料更新失败");
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getClass().getSimpleName() + " - " + e.getMessage());
        } finally {
            try {
                String jsonResponse = gson.toJson(result);
                out = response.getWriter();
                out.print(jsonResponse);
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }
    
    // 生成唯一文件名
    private String generateUniqueFileName(String originalFileName) {
        String extension = "";
        if (originalFileName != null) {
            int dotIndex = originalFileName.lastIndexOf('.');
            if (dotIndex > 0) {
                extension = originalFileName.substring(dotIndex);
            }
        }
        return UUID.randomUUID().toString() + extension;
    }
}